ScrollBarDirection =
    Enum {
    "LeftToRight",
    "TopToBottom",
    "RightToLeft",
    "BottomToTop"
}
ScrollBarEvent =RegisterEvents{
    "ValueChanged"
}

local function setScrollValue(self, val)
    self._scrollValue = val
    self:emit(ScrollBarEvent.ValueChanged, val)
end
local function onDragHandleMoved(self)
    if self.direction == ScrollBarDirection.LeftToRight then
        setScrollValue(self, self.handle.dragPercentX)
    elseif self.direction == ScrollBarDirection.TopToBottom then
        setScrollValue(self, self.handle.dragPercentY)
    end
end

ScrollBar = {
    props = {
        _direction = ScrollBarDirection.LeftToRight,
        _scrollValue = 0
    },
    gets = {
        scrollValue = function (self)
            return self._scrollValue
        end,
        direction = function (self)
            return self._direction
        end,
        handle = function (self)
            return self._handle
        end
    },
    sets = {
        scrollValue = function (self, key, val)
            setScrollValue(self, val)
            self:updateScrollBarHandle()
        end,
        direction = function (self, key, val)
            self._direction = val
        end,
        handle = function (self, key, val)
            if self._handle then
                self._handle:off(NodeEvent.OnDragMoved, onDragHandleMoved, self)
            end
            self._handle = val
            val:on(NodeEvent.OnDragMoved, onDragHandleMoved, self)
        end
    }
}

function ScrollBar:ctor()
    
end

function ScrollBar:updateScrollBarHandle()
    if self.handle then
        if self.direction == ScrollBarDirection.LeftToRight then
            self.handle.dragPercentX = self.scrollValue
        elseif self.direction == ScrollBarDirection.RightToLeft then
            self.handle.dragPercentX = 1 - self.scrollValue
        elseif self.direction == ScrollBarDirection.TopToBottom then
            self.handle.dragPercentY = self.scrollValue
        elseif self.direction == ScrollBarDirection.BottomToTop then
            self.handle.dragPercentY = 1 - self.scrollValue
        end
    end
end

function Node.ScrollBar(args)
    local node = Node.Scale9("roundedBorderBox48")
    node:addComponent(ScrollBar):wh(200, 20)
    node.color = Color.new(0.4, 0.4, 0.4, 1)

    local handle = Node.Scale9("roundedBorderBox48"):wh(20, 20)
    handle:addTo(node)
    handle:addComponent(Drag)
    handle.dragLimitMode = DragLimitMode.InsideParent
    if args and args.direction then
        node.direction = args.direction
        if node.direction == ScrollBarDirection.LeftToRight or node.direction == ScrollBarDirection.RightToLeft then
            node:wh(200, 20)
        else
            node:wh(20, 200)
        end
    end
    node.handle = handle
    return node
end
